package com.yeren.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.yeren.entity.WeixinUserInfo;
import com.yeren.service.WeixinUserInfoService;
import com.yeren.service.impl.WeixinUserInfoServiceImpl;
import com.yeren.utils.PageBean;

/**
 * 微信用户信息核心处理类
 * 
 * @author liubiao
 *
 */
public class WeixinUserInfoServlet extends HttpServlet {
	WeixinUserInfoService weixinUserInfoService = new WeixinUserInfoServiceImpl();
	private PrintWriter out;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String action = req.getParameter("action");
		if ("list".equals(action)) {
			System.out.println("333333333333333333333333333333333333");
			list(req, resp);

		} else if ("delete".equals(action)) {
			System.out.println("44444444444444444444444444444444444");
			delete(req, resp);
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("55555555555555555555555555555555555");
		WeixinUserInfo weixinUserInfo = new WeixinUserInfo();
		// ???
		weixinUserInfo.setNickname(request.getParameter("nickname"));
		System.out.println("nickname--------------->>>"
				+ request.getParameter("nickname"));
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		PageBean pageBean = new PageBean(Integer.parseInt(page),
				Integer.parseInt(rows));
		List<WeixinUserInfo> list = weixinUserInfoService.findAll(
				weixinUserInfo, pageBean);
		System.out.println("6666666666666666666666666666666666");
		System.out.println("list-------------->>>" + list.size());
		JSONObject obj = new JSONObject();
		obj.put("total", weixinUserInfoService.getSum());
		obj.put("rows", list);
		PrintWriter out = response.getWriter();
		out.print(obj);
		out.flush();
		out.close();
	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("77777777777777777777777777777777");
		String openid = request.getParameter("openId");
		System.out.println("openid--------------->>>" + openid);
		int delete = weixinUserInfoService.delete(openid);
		System.out.println("delete--------------->>>" + delete);
		out = response.getWriter();
		if (delete == 1) {
			out.write("1");
			out.flush();
			out.close();
		} else {
			out.write("0");
			out.flush();
			out.close();
		}
	}
}
